//
//  MMGPictureSelectorViewController.swift
//  MyMicroblog
//
//  Created by Mac on 17/1/13.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let items: CGFloat = 3
private let itemCountMax: CGFloat = 9
private let itemMargin: CGFloat = 5
private let itemWidth = (ScreenWidth - (items + 1) * itemMargin) / CGFloat(items)

class MMGPictureSelectorViewController: UICollectionViewController {
    var selectorImages: [UIImage] = [UIImage]()
    
    override init(collectionViewLayout layout: UICollectionViewLayout) {
        super.init(collectionViewLayout: layout)
        let flowLayout = layout as? UICollectionViewFlowLayout ?? UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
    }
    //  MAKR: 不允许使用 xib 或 sb 创建
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: 重写 viewDidLoad 方法
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.backgroundColor = UIColor.white
        self.collectionView!.register(MMGPictureSelectorViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
}

//MARK:
//MARK: 分类中实现 collectionView 数据源方法
extension MMGPictureSelectorViewController {
    // MARK: 获取组数
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    // MARK: 获取列数
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = self.selectorImages.count == Int(itemCountMax) ? 0 : 1
        return self.selectorImages.count + delta
    }
    // MARK: 获取单元格
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MMGPictureSelectorViewCell
        if indexPath.item == self.selectorImages.count {
            cell.image = nil
        }else{
            cell.image = self.selectorImages[indexPath.item]
        }
        cell.delegate = self
        return cell
    }
}
// MARK:
// MARK: 控制器分类中实现 UIImagePickerControllerDelegate 的代理方法
extension MMGPictureSelectorViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // MARK: 将获取的图片传递给选择控制器
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        if selectorImages.count > Int(itemCountMax) {
            picker.dismiss(animated: true, completion: nil)
            return
        }
        self.selectorImages.append(image.scaleImage(Width: ScreenWidth))
        // MARK: 实现此方法,在操作完成后需要手动 dismiss
        picker.dismiss(animated: true, completion: nil)
        self.collectionView?.reloadData()
    }
    
}

// MARK:
// MARK: 分类中实现 cell 代理方法
extension MMGPictureSelectorViewController: MMGPictureSelectorViewCellDelegate {

    // MARK: 用户选择投图片方法实现
    func userWillChosePicture(cell: MMGPictureSelectorViewCell) {
        // 实例化图片选择器
        let imagePicker = UIImagePickerController()
        // 设置选择器的代理
        imagePicker.delegate = self
        // modal 到图片选择器
        self.present(imagePicker, animated: true, completion: nil)
    }
    // MARK: 用户移除图片方法选择
    func userWillRemovePicture(cell: MMGPictureSelectorViewCell) {
        // 选中 cell 的序号
        let index = self.collectionView?.indexPath(for: cell)?.item
        // 移除对应序号的图片
        self.selectorImages.remove(at: index!)
        // 刷新页面
        self.collectionView?.reloadData()
        if self.selectorImages.count == 0 {
            self.removeFromParentViewController()
        }
    }
}

// MARK:
// MARK: 自定义单元格代理协议
@objc protocol MMGPictureSelectorViewCellDelegate: NSObjectProtocol {
    // MARK: 用户选择图片代理方法(可选)
    @objc optional func userWillChosePicture(cell: MMGPictureSelectorViewCell)
    // MARK: 用户移除图片代理方法(可选)
    @objc optional func userWillRemovePicture(cell: MMGPictureSelectorViewCell)
}

// MARK:
// MARK: 自定义单元格
class MMGPictureSelectorViewCell: UICollectionViewCell {
    
    var delegate: MMGPictureSelectorViewCellDelegate?
    var image: UIImage? {
        didSet {
            selectorButton.setImage(image, for: .normal)
            escButton.isHidden = image == nil
        }
    }
    
    // MARK: 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        buildPictureSelectorCellUI()
    }
    
    // MARK: 禁止使用 xib 和 SB 实例化 cell 对象
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 点击选择图片方法
    @objc private func clickSelectorButton() {
        if image != nil {
            return
        }
        if delegate != nil {
            self.delegate?.userWillChosePicture!(cell: self)
        }
    }
    // MARK: 点击取消图片选择的方法
    @objc private func clickEscButton() {
        if delegate != nil {
            self.delegate?.userWillRemovePicture!(cell: self)
        }
    }
    
    // MARK: 搭建 cell 界面
    private func buildPictureSelectorCellUI() {
        
        contentView.addSubview(selectorButton)
        selectorButton.addSubview(escButton)
        // 设置约束
        selectorButton.frame = self.bounds
        escButton.frame.origin.x = self.frame.width - escButton.frame.width
        // 监听点击事件
        selectorButton.addTarget(self, action: #selector(clickSelectorButton), for: .touchUpInside)
        escButton.addTarget(self, action: #selector(clickEscButton), for: .touchUpInside)
    }
    
    func test(){
    
        print(123);
    }
    
    // MARK: 提供选择图片按钮
    lazy var selectorButton: UIButton = {
        let selBtn = UIButton()
        selBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        selBtn.imageView?.contentMode = .scaleAspectFill
        
        return selBtn
    }()
    // MARK: 懒加载图片移除按钮
    lazy var escButton: UIButton = {
        
        let escBtn = UIButton()
        escBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        escBtn.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
//        escBtn.sizeToFit()
        return escBtn
    }()
    
    // MARK:
    // MARK: 已知移除按钮的图片尺寸过小,点击范围不满足要求,无法完成点击,苹果官方默认点击范围是44,44,测试范围为40,40之后才会满足点击要求,这种方式实现简单方便,但可能使图片失真,而且会影响整体布局事件
    // MARK: 解决方法2 - 重写按钮的点击范围,当点击范围不足44时,强制提升到44,这种方式可以解决图片因为按钮尺寸过大而失真的问题,但是模拟器不容易表现出来,因为中心点位置不响应事件
    // MARK:
    
}









